/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ai;
import java.util.*;

/**
 *
 * @author root
 */
public class ConcatExp extends LexExp {
    public ConcatExp(){
        mExpList = new LinkedList<LexExp>();
    }
    public ConcatExp(LinkedList<LexExp> pExpList){
        mExpList = pExpList;
    }
    public void addExp(LexExp pExp){
        //System.out.println("ConcatExp.addExp(Expression " + pExp + ")");
        mExpList.add(pExp);
    }
    public LexExp substitute(String pLabelName, String pString){
        LinkedList<LexExp> lExpList = new LinkedList<LexExp>();
        for (LexExp e : mExpList){
            LexExp apa = e.substitute(pLabelName, pString);
            lExpList.add(apa);
        }
        
        if (lExpList.size() > 1) {            
            LinkedList<LexExp> lNewList = new LinkedList<LexExp>();
            do
            {
                LexExp e1 = lExpList.pollFirst();
                LexExp e2 = lExpList.pollFirst();
                
                if ((e1 instanceof StringExp) && (e2 instanceof StringExp)) {
                    lExpList.addFirst(new StringExp(((StringExp)e1).getString() + ((StringExp)e2).getString()));
                }
                else {
                    lNewList.add(e1);                    
                    lExpList.addFirst(e2);
                }
            } while(lExpList.size() > 1);
            
            if (lExpList.size() != 0) {
                lNewList.add(lExpList.pollFirst());
            }
            lExpList = lNewList;
        }
        
        if (lExpList.size() == 1){
            return lExpList.pollFirst();
        }
        else {
            return new ConcatExp(lExpList);
        }
    }
    private LinkedList<LexExp> mExpList;
}
